package com.meterhuang.thread.foobar;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 多线程
 *
 * @author meterhuang
 * @date 2021/09/08 15:45
 */
@Slf4j
public class FooBarBlockingQueue {

	private int n;

	private BlockingQueue<Integer> bar = new LinkedBlockingQueue<>(1);

	private BlockingQueue<Integer> foo = new LinkedBlockingQueue<>(1);

	public FooBarBlockingQueue(int n) {
		this.n = n;
	}

	public void foo(Runnable printFoo) throws InterruptedException {
		for (int i = 0; i < n; i++) {
			log.info("foo queue size: {}", foo.size());
			foo.put(i);
			printFoo.run();
			bar.put(i);
		}
	}

	public void bar(Runnable printBar) throws InterruptedException {
		for (int i = 0; i < n; i++) {
			log.info("bar queue size: {}", bar.size());
			bar.take();
			printBar.run();
			foo.take();
		}
	}

}
